//
//  YTPromptView.m
//  CityYouTian
//
//  Created by 清正 on 16/4/13.
//  Copyright © 2016年 qz. All rights reserved.
//
#import "AppToast.h"

@interface AppToast()

@property (nonatomic, strong) NSTimer *timer;

@end

//获取屏幕宽度
#define KScreenWidth  [UIScreen mainScreen].bounds.size.width
//获取屏幕高度
#define KScreenHeight [UIScreen mainScreen].bounds.size.height

#define FoutOfSize 13.0

@implementation AppToast {
    UIImageView *_bgImageView;
}

static AppToast *g_instance = nil;

+ (instancetype )shareInstance {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        g_instance = [[AppToast alloc] init];
    });
    return g_instance;
}

- (void)dealloc {
    [_timer invalidate];
    _timer = nil;
}

- (void)dismiss {
    [SVProgressHUD dismiss];
}

+ (void)showStatusWithString:(NSString *)string {
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeNone];
    [SVProgressHUD setMinimumSize:CGSizeMake(70, 70)];
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleLight];
    [SVProgressHUD setBackgroundColor:[UIColor colorWithRed:0.95 green:0.95 blue:0.95 alpha:1.00]];
    [SVProgressHUD setDefaultAnimationType:SVProgressHUDAnimationTypeNative];
    [SVProgressHUD showWithStatus:string];
}

+ (void)dismiss {
    [SVProgressHUD dismiss];
}

+ (void)showSuccessWithString:(NSString *)string {
    [SVProgressHUD showSuccessWithStatus:string];
    [SVProgressHUD setMinimumSize:CGSizeMake(70, 70)];
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleLight];
    AppToast *tools = [AppToast shareInstance];
    [tools.timer invalidate];
    tools.timer = nil;
    tools.timer = [NSTimer timerWithTimeInterval:0.7 target:tools selector:@selector(dismiss) userInfo:nil repeats:NO];
}

+ (void)showErrorWithString:(NSString *)string {
    [SVProgressHUD showErrorWithStatus:string];
    [SVProgressHUD setMinimumSize:CGSizeMake(70, 70)];
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
    AppToast *tools = [AppToast shareInstance];
    [tools.timer invalidate];
    tools.timer = nil;
    tools.timer = [NSTimer timerWithTimeInterval:0.7 target:tools selector:@selector(dismiss) userInfo:nil repeats:NO];
}

+ (void)showStatusWithString:(NSString *)string hideAfterDelay:(CGFloat)delay {
    [SVProgressHUD showWithStatus:string];
    [SVProgressHUD setMinimumSize:CGSizeMake(70, 70)];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeClear];
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleLight];
    [SVProgressHUD setDefaultAnimationType:SVProgressHUDAnimationTypeNative];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delay * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [SVProgressHUD dismiss];
    });
}
//** 零时处理
+ (void)showFileWithString:(NSString *)string view:(UIView *)view {
    if (!view) {
        [AppToast showFileWithString:string];
        return;
    }

    [AppToast dismiss];
    UIImageView *imageView =[[AppToast shareInstance] imageView:string delay:2];
    
    if (imageView.hidden) {
        imageView.alpha = 1;
        imageView.hidden=NO;
    }
    
    UILabel *label =(UILabel*)imageView.subviews[0];
    label.center =CGPointMake(CGRectGetWidth(view.frame)/2, CGRectGetHeight(view.frame)/2);
    
    [view addSubview:imageView];
}
// */

+ (void)showFileWithString:(NSString *)string {
    CGSize labelSize =[AppToast calculateTextHeight:string];
    if (![NSThread isMainThread]) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [AppToast showFileWithString:string OffsetY:KScreenHeight/2-50-labelSize.height-50];
        });
    } else {
        [AppToast showFileWithString:string OffsetY:KScreenHeight/2-50-labelSize.height-50];
    }
}

+ (void)showFileWithString:(NSString *)string OffsetY:(CGFloat)Y {
    UIImageView *imageView =[[AppToast shareInstance] imageView:string delay:2];
    
    if (imageView.hidden) {
        imageView.alpha = 1;
        imageView.hidden=NO;
    }
    
    UILabel *label =(UILabel*)imageView.subviews[0];
    label.center =CGPointMake(KScreenWidth/2, KScreenHeight/2+Y);
    
    UIWindow *window =[[UIApplication sharedApplication] keyWindow];
    [window insertSubview:imageView atIndex:window.subviews.count];
    /*
    UIViewController *topVC = [AppToast toast_currentShowTopVC];
    [topVC.view addSubview:imageView];
     */
}

- (UIImageView*)imageView:(NSString*)string delay:(CGFloat)delay {
    [AppToast dismiss];
    if (!string || string.length ==0) {
        return nil;
    }
    UILabel *label =(UILabel*)_bgImageView.subviews[0];
    if (!_bgImageView) {
        _bgImageView=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, KScreenWidth, KScreenHeight)];
        _bgImageView.alpha = 1;
        _bgImageView.backgroundColor=[UIColor clearColor];
        
        label = [[UILabel alloc]initWithFrame:CGRectZero];
        label.center =CGPointMake(KScreenWidth/2, KScreenHeight-KScreenHeight/4);
        label.textColor =[UIColor whiteColor];
        label.backgroundColor =[UIColor colorWithWhite:0 alpha:0.8];
        label.textAlignment =NSTextAlignmentCenter;
        label.font=[UIFont systemFontOfSize:FoutOfSize];
        label.numberOfLines =0;
        label.text =@"";
        label.layer.cornerRadius =5;
        label.clipsToBounds =YES;
        [_bgImageView addSubview:label];
    }
    CGSize labelSize =[AppToast calculateTextHeight:string];
    label.bounds =CGRectMake(0, 0, labelSize.width+20, labelSize.height+20);
    label.text =string;
    // 取消延迟执行
    [AppToast cancelPreviousPerformRequestsWithTarget:[AppToast shareInstance] selector:@selector(deleteSelfView:) object:label];
    // 开启延迟执行
    [[AppToast shareInstance] performSelector:@selector(deleteSelfView:) withObject:label afterDelay:delay+0.5];

    return _bgImageView;
}

- (void)deleteSelfView:(UILabel*)label {
    [UIView animateWithDuration:0.5 animations:^{
        _bgImageView.alpha = 0;
    } completion:^(BOOL finished) {
        _bgImageView.hidden=YES;
    }];
}

+ (CGSize)calculateTextHeight:(NSString*)string {
    CGRect textRect=[string boundingRectWithSize:CGSizeMake(KScreenWidth-60, CGFLOAT_MAX) options:NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:FoutOfSize]} context:nil];
    return textRect.size;
}

+ (UIViewController *)toast_currentShowTopVC {
    UIViewController *top = [UIApplication sharedApplication].keyWindow.rootViewController;
    while (top.presentedViewController) {
        top = top.presentedViewController;
    }
    if ([top isKindOfClass:[UINavigationController class]]) {
        UINavigationController *nav = (UINavigationController *)top;
        return nav.topViewController;
    } else {
        return top;
    }
}

@end
